package Link;

public class BM7 {
    public class ListNode {
        int val;
        BM13.ListNode next = null;
        public ListNode(int val) {
            this.val = val;
        }
    }

    //链表中环的入口结点
    public ListNode hasCycle(ListNode head) {
        if (head == null) {
            return  null;
        }
        ListNode slow = head;
        ListNode fast = head;

        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                return slow;
            }
        }
        return null;
    }

    public ListNode EntryNodeOfLoop(ListNode pHead) {
        ListNode slow = hasCycle(pHead);
        if (slow == null) {
            return null;
        }

        ListNode fast = pHead;

        while (fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}
